from playwright.sync_api import Playwright, sync_playwright
import time
from service.SlidePositionService import get_gap_position


def handle_response(response):
    # 打印所有响应的 URL


    # 检查是否是登录接口（根据实际 URL 调整）
    if "login2" in response.url :
        try:
            # 如果是 JSON 响应，解析它
            json_data = response.json()
            print("登录接口响应:", json_data)
        except:
            # 如果不是 JSON，打印原始文本
            print("登录接口响应（非 JSON）:", response.text())



def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.on("response", handle_response)
    page.goto("http://jlyw.hebjlzy.com/login")
    page.get_by_role("textbox", name="请输入统一社会信用代码或身份证号").click()
    page.get_by_role("textbox", name="请输入统一社会信用代码或身份证号").fill("999901234567890HPG")
    page.get_by_role("textbox", name="请输入密码").click()
    page.get_by_role("textbox", name="请输入密码").fill("hpg123789")
    page.get_by_role("button", name="登录").click()
    # 2. 等待滑块和 Canvas 加载
    page.wait_for_selector("#circle", state="visible")  # 滑块元素
    page.wait_for_selector("#bg_canvas", state="visible")  # 背景 Canvas
    image_data = page.evaluate("document.getElementById('bg_canvas').toDataURL('image/png').split(',')[1]")


    gap_x = get_gap_position(image_data)
    print(f"检测到缺口位置: {gap_x}px")

    # 4. 模拟人类拖动行为
    slider = page.query_selector("#circle")
    slider_bbox = slider.bounding_box()
    start_x = slider_bbox["x"] + slider_bbox["width"] / 2
    start_y = slider_bbox["y"] + slider_bbox["height"] / 2

    # 拖动到缺口位置（增加随机偏移模拟人类操作）
    target_x = start_x + gap_x + 8  # +5 是为了对齐缺口

    # 按下鼠标
    page.mouse.move(start_x, start_y)
    page.mouse.down()

    # 模拟人类拖动：分多次移动，带有随机抖动
    steps = 20
    for i in range(steps):
        x = start_x + (target_x - start_x) * (i / steps)
        y = start_y + (i % 3 - 1) * 2  # 随机垂直抖动（-2, 0, 2）
        page.mouse.move(x, y)
        time.sleep(0.02)  # 短暂停顿

    # 释放鼠标
    page.mouse.up()

    # 5. 验证是否成功（根据页面反馈调整）
    success = page.query_selector(".popup-success")  # 替换为实际的成功提示元素
    if success:
        print("验证成功！")
    else:
        print("验证失败，尝试重试...")



    # 保持浏览器打开
    input("按回车键关闭浏览器...")
    browser.close()

    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)
